/*
 * GroupFormController.java
 *
 * Created on October 27, 2008, 6:29 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.vacuela.publishmx.web.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.util.WebUtils;
import org.vacuela.publishmx.constant.Constants;
import org.vacuela.publishmx.context.ServiceContext;
import org.vacuela.publishmx.context.ServiceContextImpl;
import org.vacuela.publishmx.domains.Group;
import org.vacuela.publishmx.services.AdminService;
import org.vacuela.publishmx.services.ContactBookService;
import org.vacuela.publishmx.util.PublishUtil;
import org.vacuela.publishmx.web.bean.GroupForm;
import org.vacuela.publishmx.web.bean.UserSession;

/**
 *
 * @author nestor.carrasco
 */
public class GroupFormController extends SimpleFormController {    
    
    private ContactBookService bookSvc;   
    
    
    /** Creates a new instance of GroupFormController */
    public GroupFormController() {
        setSessionForm(true);
        setValidateOnBinding(false);
        setCommandName("groupForm");
        setFormView("group/groupManagement");
    }
    
     protected Map referenceData(HttpServletRequest request) throws Exception {
        Map model = new HashMap();
        ServiceContext context = new ServiceContextImpl();
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
        context.setAttribute("userId", userSession.getUserDomain().getId());
         this.bookSvc.getGroupsByUserId(context);
        List<Group> myGroupsList  = (List<Group>)context.getAttribute("groupList");
        model.put("groupList",myGroupsList);
        return model;
    }
    
    
     protected Object formBackingObject(HttpServletRequest request) throws Exception {
        String groupId = PublishUtil.checkNull(request.getParameter("groupAction"),"");
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
        
        if ( "".equals(groupId)){
            return new GroupForm();
        }
        else {
             ServiceContext context = new ServiceContextImpl();
             Group group = new Group();
             group.setId(new Integer(groupId));
             group.setUserId(userSession.getUserDomain().getId());
             context.setAttribute("groupDomain",group);
             this.bookSvc.getGroupById(context);
             group = (Group)context.getAttribute("group");
            return new  GroupForm( group);
        }
    
     }
     
     protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
			throws Exception {

		GroupForm groupForm = (GroupForm) command;
		Group group = groupForm.getGroup();
		
		errors.setNestedPath("group");
		getValidator().validate(group, errors);
		errors.setNestedPath("");

     }     
      protected ModelAndView onSubmit(
            HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        
        GroupForm groupForm = (GroupForm)command;
        ServiceContext context = new ServiceContextImpl();
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
        groupForm.getGroup().setUserId(userSession.getUserDomain().getId());
        context.setAttribute("groupDomain", groupForm.getGroup());
        try {           
            this.bookSvc.saveUpdateGroup(context);
        } catch (DataIntegrityViolationException ex) {
            errors.rejectValue("group.groupName", "GROUP_NAME_ALREADY_EXISTS",
                    "Group Name already exists: choose a different ID.");
            return showForm(request, response, errors);
        }
        return super.onSubmit(request, response, command, errors);
      }

    public void setContactBookService(ContactBookService bookSvc) {
        this.bookSvc = bookSvc;
    }
}
